package com.sicau.smarttraceplatform.common.exceptioncatchandhandle;

import com.sicau.smarttraceplatform.common.returning.ResultData;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 *
 * @author sxt
 * @version : 1.0.0
 */
@RestControllerAdvice
public class MExceptionHandler {

    /**
     * 默认的错误发生但未捕获的提示语句
     */
    private static final String DEFAULT_EXCEPTION_MSG = "未捕获到错误信息";

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultData<String> missingServletRequestParameterException(MissingServletRequestParameterException e) {
        return getResultData(e, "缺少参数: " + e.getParameterName());
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.OK)
    public ResultData<String> defaultException(Exception e) {
        return getResultData(e);
    }


    /**
     * 设置错误响应信息
     *
     * @param e 异常
     * @return 错误响应信息
     */
    private ResultData<String> getResultData(Exception e) {
        return getResultData(e, null);
    }

    /**
     * 设置错误响应信息
     *
     * @param e      异常
     * @param errMsg 错误提示
     * @return 错误响应信息
     */
    private ResultData<String> getResultData(Exception e, String errMsg) {
        ResultData<String> rs = new ResultData<String>()
                .FAILED();
        if (e != null) {
            rs.setObj(e.getMessage());
        } else {
            rs.setObj(DEFAULT_EXCEPTION_MSG);
        }
        if (!StringUtils.isEmpty(errMsg)) {
            rs.setResultIns(errMsg);
        }
        return rs;
    }

}
